import {
  getStyle
} from "../utils/tools";

export default {
  inserted(el) {
    // 获取节点
    const oImgWrap = el,
      oMagWrap = oImgWrap.querySelector('.mag-wrap'),
      oMagImg = oMagWrap.querySelector('.mag-img'),
      //获取图片宽度/高度
      imgWidth = getStyle(oImgWrap, 'width'), //375
      imgHeight = getStyle(oImgWrap, 'height'), //471
      //获取放大镜框框的宽度/高度
      magWidth = getStyle(oMagWrap, 'width'), //100
      magHeight = getStyle(oMagWrap, 'height'), //100
      //获取图片到浏览器顶侧/左侧的距离
      imgX = oImgWrap.offsetLeft,
      imgY = oImgWrap.offsetTop;

    const init = () => {
      bindEvent();
    }

    function bindEvent() {
      oImgWrap.addEventListener('mouseover', function (e) {
        //鼠标移入时显示放大镜框框
        oMagWrap.className += ' show';

        //
        showMag(getXY(e).x, getXY(e).y);

        document.addEventListener('mousemove', handleMouseMove, false);
      }, false);

      oImgWrap.addEventListener('mouseout', handleMouseOut, false);
    }

    function handleMouseMove(e) {
      const {
        x,
        y,
        mouseX,
        mouseY
      } = getXY(e);

      showMag(x, y, mouseX, mouseY);
    }

    function handleMouseOut() {
      //鼠标离开时隐藏放大镜框框
      oMagWrap.className = 'mag-wrap';

      //解除绑定
      document.removeEventListener('mousemove', handleMouseMove, false);
    }

    function showMag(x, y, mouseX, mouseY) {
      //放大镜框随鼠标移动
      oMagWrap.style.left = x + 'px';
      oMagWrap.style.top = y + 'px';

      //图片反方向移动
      oMagImg.style.left = -x + 'px';
      oMagImg.style.top = -y + 'px';

      if (mouseX < 0 || mouseY < 0 || mouseX > imgWidth || mouseY > imgHeight) {
        oMagWrap.className = 'mag-wrap';

        document.removeEventListener('mousemove', handleMouseMove, false);
      }
    }

    function getXY(e) {

      return {
        //找到当前鼠标位置: 鼠标页面位置 - 图片位置顶侧距离 - 放大镜框宽度/2
        x: e.pageX - imgX - magWidth / 2,
        y: e.pageY - imgY - magHeight / 2,
        //找到图片边界位置: 鼠标页面位置 - 鼠标距离图片位置
        mouseX: e.pageX - imgX,
        mouseY: e.pageY - imgY
      }
    }


    init();
  }
}